package edu.cebanc.spring.biblioteca.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import edu.cebanc.spring.biblioteca.domain.Book;

@Repository("booksDAO")
public class BooksDAOimpl implements BooksDAO {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void saveBook(Book book) {
		sessionFactory.getCurrentSession().saveOrUpdate(book);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Book> listBooks() {
		return (List<Book>) sessionFactory.getCurrentSession()
				.createCriteria(Book.class)
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
	}

	@Override
	public Book getBook(int id) {
		return (Book) sessionFactory.getCurrentSession().get(Book.class, id);
	}

	@Override
	public void delBook(Book book) {
		book.setAutores(null);
		book.setGeneros(null);
		sessionFactory.getCurrentSession().delete(book);
	}

}
